﻿using System.Diagnostics;

using il2lua.TypeSystem;

using Mono.Cecil;

using Stub;

public static class NameSpaceMixins
{
    public static string GetIdentifier(this TypeDefinition type)
    {
        var rename = type.FindAttribute<RenameAttribute>();
        if (rename != null)
        {
            return rename.Name;
        }
        return ToGenericFullName(type.Name);
    }

    public static string GetIdentifier(this FieldDefinition field)
    {
        var rename = field.FindAttribute<RenameAttribute>();
        if (rename != null)
        {
            return rename.Name;
        }
        return ToGenericFullName(field.Name);
    }

    public static string GetIdentifier(this MethodDefinition method)
    {
        var rename = method.FindAttribute<RenameAttribute>();
        if (rename != null)
        {
            return rename.Name;
        }
        return ToGenericFullName(method.Name);
    }

    public static INameSpace GetNameSpace(this INameSpace self, string[] path)
    {
        return self.GetNameSpace(0, path);
    }

    public static INameSpace GetNameSpace(this INameSpace self, int index, string[] path)
    {
        if (index < path.Length)
        {
            var name = path[index];
            if (IsNullOrEmpty(name))
            {
                Debug.Assert(path.Length == index + 1);
                return self;
            }
            var childs = self.Childs;
            for (var i = 0; i < childs.Count; i++)
            {
                if (childs[i].Name == name)
                    return childs[i].GetNameSpace(index + 1, path);
            }
            return new ILNameSpace(name, self).GetNameSpace(index + 1, path);
        }
        return self;
    }
}

